package com.xingzhe.pengji.security.support;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.xingzhe.pengji.security.domain.User;
import com.xingzhe.pengji.security.services.UserService;

/**
 * @Title ： 三江学院 毕业设计
 * @Description ：项目实现的用户查询服务,将用户信息查询出来
 * @author ：LuFengLiang
 * @Company: IT行者工作室
 * @Copyright: Copyright (c) 2012-2-24
 * @version ： 1.0
 */
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService
{
    @Autowired
    private UserService<User> userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException
    {
        Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        // 取得用户的权限
        auths = userService.loadUserAuthoritiesByName(userName);

        User user = (User) userService.getUserByAccount(userName);
        if (null == user)
        {
            throw new UsernameNotFoundException(userName);
        }

        User u = new User(user.getName(), user.getEmail(), user.getAccount(), user.getPassword(), user.getIsSys(),
                user.getEnabled(), user.getAccountNonLocked(), user.getAccountNonExpired(),
                user.getCredentialsNonExpired(), auths);
        return u;
    }

}
